import os
from datetime import datetime
from typing import List
import base64
from alibabacloud_facebody20191230.client import Client as facebody20191230Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_facebody20191230 import models as facebody_20191230_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient
from viapi.fileutils import FileUtils
import requests
from config import Config as myConfig

def image_repaired(local_image_path: str):

    SAVE_PATH = myConfig.PATH_IMAGE_REPAIRED
    
    access_key_id = "LTAI5tEjriqJU1PhpsG31VDA"
    access_key_secret = "jYr2LWv3ohluUvbSvnSlMkVAtcHYu4"

    # 创建客户端
    config = open_api_models.Config(
        access_key_id=access_key_id,
        access_key_secret=access_key_secret
    )
    config.endpoint = 'facebody.cn-shanghai.aliyuncs.com'
    client = facebody20191230Client(config)

    # 上传图片并获取临时URL
    file_utils = FileUtils(access_key_id, access_key_secret)
    oss_url = file_utils.get_oss_url(local_image_path, "jpg", True)
    print("临时公网URL:", oss_url)

    # 调用API增强人脸
    enhance_face_request = facebody_20191230_models.EnhanceFaceRequest(
        image_url=oss_url
    )
    runtime = util_models.RuntimeOptions()
    response = client.enhance_face_with_options(enhance_face_request, runtime)

    # 正确获取 ImageURL 的方式
    enhanced_image_url = response.body.data.image_url
    print("增强后图片URL:", enhanced_image_url)

    # 构造输出路径和新文件名
    


    # 下载并保存图像
    with requests.get(enhanced_image_url, stream=True) as r:
        r.raise_for_status()
        with open(SAVE_PATH, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)

    print(f"✅ 图像已保存至: {SAVE_PATH}")
